package com.luobu.javaee.service;

import com.luobu.javaee.domain.dto.ImgResDto;
import com.luobu.javaee.exception.DocumentException;
import com.luobu.javaee.util.FileIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImageService {
    @Value("${server.port}")
    private int serverPort;

    public List<String> encodeAllPicsBase64(Long userId, String docName){
        String projDir = System.getProperty("user.dir").replaceAll("\\\\", "\\\\\\\\");
        String userIdString = String.format("%06d", userId); // 将userId格式化为六位的字符串
        String picPath = projDir + File.separator + "static/picture" + File.separator + userIdString + File.separator + docName;
        List<String> res = new ArrayList<>();
        File storeDir = new File(picPath);
        File[] pics = storeDir.listFiles();
        for (File pic : pics){
            try{
                res.add(FileIO.readFileToString(pic));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return res;
    }

    public List<ImgResDto> uploadPic(List<MultipartFile> files, Long userId, String docName, Long archiveId) throws DocumentException, IOException {
        // 构造文档对应图片文件夹的路径
        if (archiveId == null)
            archiveId = -1L;
        String picDirRoot = FileIO.getPictureDirPath(userId, docName, archiveId);

        List<ImgResDto> imgResDtoList = new ArrayList<>();
        InetAddress ip = InetAddress.getByName("127.0.0.1");
        String serverIp = ip.getHostAddress();

        /*
            图片编码规范：
            同一次上传的图片组使用年月日时分秒 + 图片顺序方式编码
         */
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String time = dateTime.format(formatter);

        Long imgIndex = 0L;
        for (MultipartFile imageFile : files) {
            imgIndex++;
            if (imageFile != null && !imageFile.isEmpty()) {
                // 获取原始文件名
                String originalFilename = imageFile.getOriginalFilename();
                if (StringUtils.hasText(originalFilename)) {
                    // 获取图片后缀
                    String extension = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);

                    // 构建图片文件名
                    String imageName = time + String.format("%04d", imgIndex) + "." + extension;

                    // 构造完整的存储路径
                    String imagePath = picDirRoot + File.separator + imageName;

                    try {
                        // 将图片文件保存到目标路径
                        FileIO.resourcePathCheck(imagePath);
                        imageFile.transferTo(new File(imagePath));
                        ImgResDto imgResDto = new ImgResDto();
                        imgResDto.setId(imgIndex);

                        String archiveIdStr = archiveId.equals(-1L) ? "default" : String.valueOf(archiveId);
                        String urlPath = serverIp + ":" + serverPort + "/picture/" + String.format("%06d", userId) + "/" + archiveIdStr + "/" + imageName;
                        imgResDto.setURL(urlPath);
                        imgResDtoList.add(imgResDto);
                    } catch (IOException e) {
                        e.printStackTrace();
                        // 处理存储失败的情况
                    }
                }
            }
        }
        return imgResDtoList;
    }
}
